<?php

/**
 * Proxy php script is needed to get xml source of other domains
 * Otherwise you get an javascript "Access to restricted URI denied" error
 *
 * @package News Widget
 * @author Sitebase (http://www.sitebase.be)
 * @version 1.7.0
 * @license http://codecanyon.net/wiki/support/legal-terms/licensing-terms/
 * @copyright Copyright (c) 2008-2011 Sitebase (http://www.sitebase.be)
 */

// Settings
$items = array();
$limit = isset($_POST['limit']) && is_numeric($_POST['limit']) ? $_POST['limit'] : 10;
$date_format = isset($_POST['date_format']) ? $_POST['date_format'] : 'd/m/Y';
$random = isset($_POST['random']) && $_POST['random'] == 'true' ? true : false;

// Get source list
if(strstr($_POST['source'], '|')) {
	$sources = explode('|', $_POST['source']);
} else {
	$sources[] = $_POST['source'];
}

// Get sources items
foreach($sources as $source) {
	$new_items = feed_to_items($source);
	$items = array_merge($items, $new_items);
}

// sort items and return
if(!$random) {
	usort($items, array('ItemVo', 'cmpDescSort'));
} else {
	shuffle($items);
}
$show_items = array_slice($items, 0, $limit);
echo json_encode($show_items);

function feed_to_items($source) {
	global $date_format;
	
	// Cache probleem oplossen mogelijkheden?
	// google key nodig?
	// nocache=1319527126253 (datetime of zoiets)
	$separator = strstr($source, '?') ? '&' : '?';
	$src = 'http://www.google.com/uds/Gfeeds?context=0&num=10&hl=en&output=json&refreshInterval=0&q=' . urlencode($source . $separator . time()) . '&v=1.0&nocache=0';
	$json = json_decode(remote_read($src));
	
	$website_title = $json->responseData->feed->title;
	$website_link = $json->responseData->feed->link;
	
	$items = array();
	foreach($json->responseData->feed->entries as $entry) {
		$item = new ItemVo();
		$item->websiteTitle = $website_title;
		$item->websiteLink = $website_link;
		$item->title = $entry->title;
		$item->titleLink = '<a href="' . $entry->link . '">' . $entry->title . '</a>';
		$item->description = $entry->content;
		$item->date = date($date_format,strtotime($entry->publishedDate));
		$item->timestamp = strtotime($entry->publishedDate);
		$item->prettyDate = ago($item->timestamp);
		$item->link = $entry->link;
		$item->image = find_first_image($entry->content);
		$items[] = $item;
	}
	
	return $items;
}

function remote_read($source) {
	if(function_exists('curl_init')) {
		$ch = curl_init();
		$timeout = 5;
		curl_setopt($ch,CURLOPT_URL, $source);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, $timeout);
		$data = curl_exec($ch);
		curl_close($ch);
		return $data;
	} 
	if(function_exists('file_get_contents')) {
		return file_get_contents($source);
	}
	show_error('curl or file_get_contents needs to be enabled');
}

function find_first_image($content) {
	preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $content, $matches);
	$image = $matches [1] [0];
	if(empty($image)){ //Defines a default image
		return null;
	}
	return $image;
}

function ago($timestamp){
	if(!isset($timestamp) || empty($timestamp)) return '';
   $difference = time() - $timestamp;
   $periods = array("second", "minute", "hour", "day", "week", "month", "years", "decade");
   $lengths = array("60","60","24","7","4.35","12","10");
   for($j = 0; $difference >= $lengths[$j]; $j++)
   $difference /= $lengths[$j];
   $difference = round($difference);
   if($difference != 1) $periods[$j].= "s";
   $text = "$difference $periods[$j]";
   return $text;
}

function show_error($message) {
	echo json_encode(array('error' => $message));
	exit();
}

class ItemVo {
	public $websiteTitle;
	public $websiteLink;
	public $title;
	public $titleLink;
	public $description;
	public $timestamp;
	public $date;
	public $prettyDate;
	public $link;
	public $image;
	
	public function cmpAscSort($m, $n) {
	    if ($m->timestamp == $n->timestamp) {
	        return 0;
	    }
  		return ($m->timestamp < $n->timestamp) ? -1 : 1;
	}
	
	public function cmpDescSort($m, $n) {
		if ($m->timestamp == $n->timestamp) {
			return 0;
		}
		return ($m->timestamp > $n->timestamp) ? -1 : 1;
	}
}

?>